<%@ page import="cn.labbook.bluetooth.constant.AmmeterConstant" %>
<%@ page import="cn.labbook.bluetooth.common.TokenManager" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <%
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    %>
    <base href="<%=basePath%>">
    <title>蓝牙电表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <link rel="stylesheet" type="text/css" href="assets/css/admin/reset.css"/>
    <link rel="stylesheet" type="text/css" href="assets/plugins/layui/css/layui.css">
    <link rel="stylesheet" type="text/css" href="//at.alicdn.com/t/font_893379_qj8lfap4ylj.css"/>
</head>
<style>
    /*让徽章上下居中*/
    .layui-badge {
        top: 50%;
        transform: translateY(-50%);
    }

    .search {
        margin: 30px 80px;
        position: relative;

    }

    .search input {
        position: absolute;
        top: 0;
        left: 0;
        width: 300px;
        height: 35px;
        outline: none;
        border: 1px solid #979797;
        text-indent: 10px;
    }

    .search .btn {
        position: absolute;
        top: 0;
        left: 301px;
        width: 80px;
        height: 37px;
        border: 1px solid #979797;
        background: linear-gradient(to bottom, #f9f9f9, #ededed);
        font-size: 16px;
        outline: none;

    }

    ul {
        margin-left: 64px;
        margin-top: 44px;
        width: 381px;
        border: 1px solid #979797;
        position: absolute;
        top: 66px;
        left: 80px;
        box-sizing: border-box;
    }

    ul li {
        line-height: 30px;
        color: #7a77c8;
        cursor: pointer;
        padding: 0 10px;
        box-sizing: border-box;
    }

    ul li:hover {
        background: #7a77c8;
        color: white;
    }

    .hidden {

        display: none;
    }

    .show {
        display: block;
    }
    .layui-table-cell .layui-form-checkbox[lay-skin="primary"]{
        top: 50%;
        transform: translateY(-50%);
    }
</style>
<body>
<div>
    <div class=" clearfix margin-15">
        <div class="layui-col-md12">
            <div class="layui-card-header">
                电表列表
            </div>
            <input type="hidden" value="<%=TokenManager.getToken().getAdminId()%>" id="der">
            <div class="layui-form layuiadmin-card-header-auto padding-tb-10 layui-card"
                 lay-filter="layadmin-userfront-formlist" id="searchForm">
                <div class="layui-form-item searchDiv" style="margin-bottom: 0">
                    <div class="layui-inline">
                        <label class="layui-form-label">经销商</label>
                        <div class="layui-input-block">
                            <select name="status" id="adminName" lay-search>
                                <option value="">请输入经销商名称</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">电表状态</label>
                        <div class="layui-input-block ">
                            <select name="status" id="status">
                                <option value="">请选择</option>
                                <option value=<%=AmmeterConstant.ACTIVATE%>>激活</option>
                                <option value=<%=AmmeterConstant.NOTACTIVATE%>>未激活</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn layuiadmin-btn-useradmin" id="search"
                                lay-filter="LAY-user-front-search">
                            <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="layui-tab-content">
                <div class="layui-btn-div">
                    <shiro:hasPermission name="manufacturers">
                        <button class="layui-btn" data-type="addPm" id="code">二维码</button>
                        <button class="layui-btn" id="template">模板导出</button>
                        <button class="layui-btn" id="excelput">模板导入</button>
                        <button class="layui-btn" id="addPm">新增</button>
                    </shiro:hasPermission>
<%--                    <shiro:hasPermission name="zkis">--%>
<%--                        <button class="layui-btn" id="server">设置费率</button>--%>
<%--                    </shiro:hasPermission>--%>
                </div>
                <table class="layui-table" id="payPmList" lay-filter="payPmList"></table>
            </div>
        </div>
    </div>
</div>
<div id="addPmDiv" class="divHideLayer">
    <form class="layui-form" lay-filter="editForm" id="editForm">
        <table class="table_all">
            <tbody>
            <tr>
                <th><span class="red">*</span>电表序列号</th>
                <td>
                    <input type="text" name="ammeterId" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th><span class="red">*</span>所属经销商</th>
                <td>
                    <%--<input type="text" name="managerId" lay-verify="required" autocomplete="off"--%>
                           <%--class="layui-input layui-form-danger" placeholder="">--%>
                        <select name="adminId" id="dealerName" lay-search>
                            <%--<option>所属经销商</option>--%>
                        </select>
                </td>
            </tr>
            </tbody>
        </table>
        <div class="layui-form-item">
            <div class="submitForm">
                <button class="layui-btn" type="button" lay-submit="" lay-filter="addSubmit" id="cancel2">提交</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancel3" onclick="hideFun()">取消</button>
            </div>
        </div>
    </form>
</div>
<div id="serverPmDiv" class="divHideLayer">
    <form class="layui-form" lay-filter="editForm" id="serverForm">
        <table class="table_all">
            <tbody>
            <tr>
                <th><span class="red">*</span>默认电表费率</th>
                <td>
                    <input type="text" name="serverPrive" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="" id="payPrice">
                </td>
            </tr>
            </tbody>
        </table>
        <div class="layui-form-item">
            <div class="submitForm">
                <button class="layui-btn" type="button" lay-submit="" lay-filter="serverSubmit" id="cancel6">提交</button>
                <button type="button" class="layui-btn layui-btn-primary" id="cancel7" onclick="hideFun()">取消</button>
            </div>
        </div>
    </form>
</div>
<div id="msgPmDiv" class="divHideLayer">
    <form class="layui-form" lay-filter="msgForm" id="msgForm">
        <table class="table_all">
            <tbody>
            <tr>
                <th><span class="red">*</span>创建时间</th>
                <td>
                    <input type="text" name="createTime" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th><span class="red">*</span>电表地址</th>
                <td>
                    <input type="text" name="location" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>电表状态</th>
                <td style="width: 75%">
                    <input type="text" name="status" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>最高充值金额</th>
                <td style="width: 75%">
                    <input type="text" name="rechargeAmount" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>总度数</th>
                <td style="width: 75%">
                    <input type="text" name="amount" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>余额</th>
                <td style="width: 75%">
                    <input type="text" name="balance" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>上传数据时间</th>
                <td style="width: 75%">
                    <input type="text" name="readingTime" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>电表服务状态</th>
                <td style="width: 75%">
                    <input type="text" name="serverStatus" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
<%--            <tr>--%>
<%--                <th style="width: 25%"><span class="red">*</span>服务到期时间</th>--%>
<%--                <td style="width: 75%">--%>
<%--                    <input type="text" name="serverTime" lay-verify="required" autocomplete="off"--%>
<%--                           class="layui-input layui-form-danger" placeholder="">--%>
<%--                </td>--%>
<%--            </tr>--%>
            <%--            <tr>--%>
            <%--                <th style="width: 25%"><span class="red">*</span>是否存在试用期</th>--%>
            <%--                <td style="width: 75%">--%>
            <%--                    <input type="text" name="tryStatus" lay-verify="required" autocomplete="off"--%>
            <%--                           class="layui-input layui-form-danger" placeholder="">--%>
            <%--                </td>--%>
            <%--            </tr>--%>
            <tr>
                <th style="width: 25%"><span class="red">*</span>是否欠费</th>
                <td style="width: 75%">
                    <input type="text" name="oweStatus" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>电表欠费是否拉闸</th>
                <td style="width: 75%">
                    <input type="text" name="switchStatus" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>电表激活时间</th>
                <td style="width: 75%">
                    <input type="text" name="activateTime" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>缴费类型</th>
                <td style="width: 75%">
                    <input type="text" name="payType" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            <tr>
                <th style="width: 25%"><span class="red">*</span>每季服务费</th>
                <td style="width: 75%">
                    <input type="text" name="payPrice" lay-verify="required" autocomplete="off"
                           class="layui-input layui-form-danger" placeholder="">
                </td>
            </tr>
            </tbody>
        </table>
        <div class="layui-form-item">
            <div class="submitForm">
                <%--<button class="layui-btn" type="button" lay-submit="" lay-filter="editSubmit" id="cancell">提交</button>--%>
                <%--<button type="button" class="layui-btn layui-btn-primary" id="cancel" onclick="hideFun()">取消</button>--%>
            </div>
        </div>
    </form>
</div>
<div style="display: none">
    <form action="ammeter/code" method="post" enctype="multipart/form-data" id="codeForm">
        <input type="file" id="file-input" name="file">
    </form>
</div>
<script type="text/html" id="barDemo">
    {{#  if(d.status == <%=AmmeterConstant.NOTACTIVATE%>){ }}
    {{#  } else if(d.status == <%=AmmeterConstant.ACTIVATE%> && d.serverStatus == <%=AmmeterConstant.serverStatus.EXPIRE%>){ }}
    <a class="btn-white btn-success layui-btn-xs" lay-event="del">关闭电表</a>
    {{#  } }}
    <a class="btn-white btn-success layui-btn-xs" lay-event="msg">详情信息</a>
    <%--<a class="btn-white btn-success layui-btn-xs" lay-event="activate">收费服务设置</a>--%>
</script>
</body>
<script src="assets/plugins/Jquery/jquery.min.js"></script>
<script src="assets/plugins/layui/layui.all.js"></script>
<script src="assets/js/common.js"></script>
<script>
    var userId = null;
    var serverData = null;
    $(function () {
        var url = "admin/select/list";

        layui.use(['table', 'form', 'laydate', 'upload'], function () {
            var table = layui.table,
                form = layui.form,
                upload = layui.upload;

            getAjaxReq(url, null, function (res) {
                var data = res.data;
                for (var i = 0; i < data.length; i++) {
                    var option = '<option value="' + data[i].adminId + '">' + data[i].adminName + '</option>'
                    $("#adminName").append(option);
                    $("#dealerName").append(option);
                    form.render('select');
                }
            });
            //上传表格批量导入
            upload.render({
                elem: '#excelput' //绑定元素
                , url: 'ammeter/excelput' //上传接口
                , accept: 'file' //允许上传的文件类型
                , auto: false
                , choose: function (obj) {
                    var fileReg = /\.xl.{1,2}$/;
                    var maxFileSize = 5 * 1024 * 1024;
                    obj.preview(function (index, file, result) {
                        var type = file.name;
                        if (type && !fileReg.test(type)) {
                            return layer.msg("文件类型只能是：xls ， xlt 或 xlsx", {icon: 0});
                        }
                        if (file.size && file.size > maxFileSize) {
                            return layer.msg("文件大小不能超过5MB", {icon: 0});
                        }
                        obj.upload(index, file);
                        loadIndex = layer.load();
                    });

                }
                , done: function (res) {
                    console.log(res);
                    //上传完毕回调
                    if (res.code) {
                        layer.msg("上传成功", {icon: 1});
                        setTimeout(function () {
                            window.location.reload();
                        }, 500)
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                    layer.close(loadIndex);
                }, error: function () {
                    layer.msg("请求异常", {icon: 0});
                    layer.close(loadIndex);
                }
            });
            //上传表格生成二维码
            $("#code").on("click", function (e) {
                $("#codeForm")[0].reset()
                $("#file-input").click();
            })
            $("#file-input").on("change", function (e) {
                var file = this.files[0];
                var fileType = file.type;
                var fileName = file.name;
                var size = file.size;
                var fileReg = /\.xl.{1,2}$/;
                var maxFileSize = 5 * 1024 * 1024;
                if (fileName && !fileReg.test(fileName)) {
                    return layer.msg("文件类型只能是：xls ， xlt 或 xlsx", {icon: 0});
                }
                if (size && size > maxFileSize) {
                    return layer.msg("文件大小不能超过5MB", {icon: 0});
                }
                $("#codeForm").submit();
            });

            var data = [
                {checkbox: true},
                {type: 'numbers', title: '序号'},
                {field: 'ammeterId', title: '电表序列号', sort: false, align: 'center'},
                {
                    field: 'status', title: '电表状态', sort: false, align: 'center', templet: function (d) {
                        if (d.status == <%=AmmeterConstant.ACTIVATE%>) return '<span class="layui-badge layui-bg-blue">激活</span>'
                        else if (d.status == <%=AmmeterConstant.NOTACTIVATE%>) return '<span class="layui-badge">未激活</span>'
                        else return '<span class="layui-badge layui-bg-cyan">未知</span>'
                    }
                },
                {field: 'location', title: '电表地址', sort: false, align: 'center'},
                {field: 'adminName', title: '经销商', sort: false, align: 'center'},
                {
                    field: 'serverStatus', title: '电表服务状态', sort: false, align: 'center', templet: function (d) {
                        if (d.serverStatus == <%=AmmeterConstant.serverStatus.NOTEXPIRE%>) return '<span class="layui-badge layui-bg-blue">未到期</span>'
                        else if (d.serverStatus == <%=AmmeterConstant.serverStatus.EXPIRE%>) return '<span class="layui-badge layui-bg-red">已到期</span>'
                        else if (d.serverStatus == <%=AmmeterConstant.serverStatus.UPCOMINGEXPIRE%>) return '<span class="layui-badge layui-bg-orange">即将到期</span>'
                        else return '<span class="layui-badge layui-bg-cyan">未知</span>'
                    }
                },
                // {field: 'serverTime', title: '服务到期时间', sort: false, align: 'center'},
                {field: 'activateTime', title: '电表激活时间', sort: false, align: 'center'},
                // {title: '操作', sort: false, align: 'center', toolbar: '#barDemo'}
            ];
            table.render(
                renderTable("#payPmList", 'ammeter/zkPage', data)
            );

            table.on('tool(payPmList)', function (obj) {
                var data = obj.data;
                userId = data.userId
                if (obj.event === "msg") {
                    layer.open({
                        type: 1,
                        title: "详情",
                        btnAlign: "c",
                        offset: ['25px'],
                        area: ['600px', '90%'],
                        content: $("#msgPmDiv"),
                        success: function () {
                            var msgStatus = msgStatusSet(data.status);
                            var serverStatus = serverStatusSet(data.serverStatus);
                            var switchStatus = switchStatusSet(data.switchStatus);
                            var oweStatus = oweStatusSet(data.oweStatus);
                            var payType = payTypeSet(data.payType);

                            form.val('msgForm', {
                                "createTime": data.createTime
                                , "location": data.location
                                , "status": msgStatus
                                , "rechargeAmount": data.rechargeAmount
                                , "amount": data.amount
                                , "balance": data.balance
                                , "readingTime": data.readingTime
                                , "serverStatus": serverStatus
                                , "serverTime": data.serverTime
                                , "tryStatus": data.tryStatus
                                , "oweStatus": oweStatus
                                , "switchStatus": switchStatus
                                , "activateTime": data.activateTime
                                , "payType": payType
                                , "payPrice": data.payPrice
                            })
                        },
                        end: function (i) {
                            layer.close(i);
                            hideWithReset("#msgPmDiv", "#msgForm")
                        }
                    });
                }
                if (obj.event === "del") {
                    layer.confirm('确定关闭电表？', function (index) {
                        postAjaxReq("ammeter/notactivate", {"ammeterId": data.ammeterId}, function (res) {
                            if (res.code == 1) {
                                obj.del();
                                layer.msg("操作成功")
                                table.reload('payPmList')
                                userId = null
                            } else {
                                layer.msg(res.msg)
                            }

                        });
                        layer.close(index);
                    })
                }
                if (obj.event === "common") {
                    layer.confirm('确定要更改为普通用户？', function (index) {
                        postAjaxReq("user/common", {"userId": data.userId}, function (res) {
                            if (res.code == 1) {
                                obj.del();
                                layer.msg("操作成功")
                                table.reload('payPmList')
                                userId = null
                            } else {
                                layer.msg(res.msg)
                            }

                        });
                        layer.close(index);
                    })
                }
                if (obj.event === "dealer") {
                    layer.confirm('确定要更改为经销商？', function (index) {
                        postAjaxReq("user/dealer", {"userId": data.userId}, function (res) {
                            if (res.code == 1) {
                                obj.del();
                                layer.msg("操作成功")
                                table.reload('payPmList')
                                userId = null
                            } else {
                                layer.msg(res.msg)
                            }

                        });
                        layer.close(index);
                    })
                }
                if (obj.event === "freeze") {
                    layer.confirm('确定要冻结该用户？', function (index) {
                        postAjaxReq("user/freeze", {"userId": data.userId}, function (res) {
                            if (res.code == 1) {
                                obj.del();
                                layer.msg("操作成功")
                                table.reload('payPmList')
                                userId = null
                            } else {
                                layer.msg(res.msg)
                            }

                        });
                        layer.close(index);
                    })
                }
            });
            form.verify({
                overdueDays: [/^[+]{0,1}(\d+)$/, '逾期天数必须是正整数']
            });
            $("#addPm").click(function () {
                var adminId = $("#der").val()
                if(adminId.toString().length<4){
                    for(var i=0;i<4-adminId.toString().length;i++){
                        adminId = "0"+adminId.toString();
                    }
                }
                layer.open({
                    type: 1,
                    title: "",
                    btnAlign: "c",
                    offset: ['150px'],
                    area: ['500px', '250px'],
                    content: $("#addPmDiv"),
                    success: function () {
                        form.val('editForm', {
                            "ammeterId": adminId
                        })
                    },
                    end: function (i) {
                        layer.close(i)
                        hideWithReset("#addPmDiv", "#editForm")
                    }
                });
            })
            form.on('submit(editSubmit)', function (obj) {
                var url = null;
                var data = obj.field
                if (!isEmpty(userId)) {
                    data.userId = userId
                    url = "ammeter/edit"
                } else
                    url = "ammeter/add"
                postAjaxReq(url, data, function (res) {
                    if (res.code == 1) {
                        layer.closeAll();
                        table.reload('payPmList');
                        layer.msg("保存成功")
                        userId = null
                    } else {
                        layer.msg(res.msg)
                    }
                })
            });
            form.on('submit(addSubmit)', function (obj) {
                var url = "ammeter/add"
                var data = obj.field
                postAjaxReq(url, data, function (res) {
                    if (res.code == 1) {
                        layer.closeAll();
                        table.reload('payPmList');
                        layer.msg("保存成功")
                    } else {
                        layer.msg(res.msg)
                    }
                })
            });

            // $("#server").click(function () {
            //     var url = "constant/get/payPrice"
            //     arrayAjaxReq(url, data, function (res) {
            //         if (res.code == 1) {
            //             console.log(res.data)
            //             $("#payPrice").val(res.data)
            //             serverData = table.checkStatus('payPmList').data;
            //             layer.open({
            //                 type: 1,
            //                 title: "电表费率设置",
            //                 btnAlign: "c",
            //                 offset: ['150px'],
            //                 area: ['400px', '200px'],
            //                 content: $("#serverPmDiv"),
            //                 success: function () {
            //
            //                 },
            //                 end: function (i) {
            //                     layer.close(i)
            //                     hideWithReset("#serverPmDiv", "#serverForm")
            //                 }
            //             });
            //         } else {
            //             layer.msg(res.msg)
            //         }
            //     })
            //
            // });
            // form.on('submit(serverSubmit)', function (obj) {
            //     var url = "constant/setServerPrive"
            //     var data = obj.field;
            //     var serverData = table.checkStatus('payPmList').data;
            //     // data.serverData = JSON.stringify(serverData);
            //     arrayAjaxReq(url, data, function (res) {
            //         if (res.code == 1) {
            //             layer.closeAll();
            //             table.reload('payPmList');
            //             layer.msg("设置成功")
            //         } else {
            //             layer.msg(res.msg)
            //         }
            //     })
            // });

            //导出模板
            $("#template").click(function () {
                var adminId = $("#adminName").val();
                if (isEmpty(adminId)) {
                    layer.msg("请选择经销商");
                } else {
                    location.href = "<%=basePath%>ammeter/template?adminId=" + adminId
                }
            });

            $("#search").click(function () {
                var adminId = $("#adminName").val(),
                    status = $("#status").val();

                table.reload('payPmList', {
                    page: {curr: 1},
                    where: {
                        adminId: adminId,
                        status: status
                    }
                })
            });
        });
    });

    $("#cancel").on("click", function () {
        layer.closeAll()
    });

    function hideFun() {
        layer.closeAll();
        userId = null
    }

    function hideWithReset(hide, reset) {
        $(hide).hide()
        $(reset)[0].reset()
    }
</script>
<script>
    $(function () {
        <!-- 获取本地数据-->

        //    获取表单元素
        var text = $("#payPrice")[0];
        //获取用来显示历史记录的列表框
        var hidden = document.getElementsByTagName('ul')[0];
        //    获取搜索按钮
        var btn = document.getElementsByClassName('btn')[0];
        // 从本地存储中获取本地数据
        //将数据转换为数组格式
        //     当键盘按键释放时触发事件
        text.onkeyup = function () {
            // 获取输入的数据
            var txt = text.value;
//         初始化一个变量用来承载查找到的数据
            var html = '';
            for (var i = 0; i < 2; i++) {
                var reg = new RegExp(txt);  //只有用构造函数方式才能传递参数
                var index = 100; //在本地数据中查找是否含有输入的内容
//            如果有，则将数据放到变量中
                if (index != -1) {
                    html += ' <li>100</li>';
                }
            }
//          将最后得到的所有数据添加到要展示的列表框中
            hidden.innerHTML = html;
//      显示列表框
            hidden.className = ' show';

        };

        // //    给历史展示框添加单击事件，利用事件委托
        // //    将点击的历史展示框中 的内容添加到搜索栏中，
        // hidden.onclick = function (e) {
        //     var li = e.target;
        //     var title = li.innerHTML;
        //     text.value = title;
        // }

    })

</script>
</body>
</html>
